﻿using System.Windows;

namespace GenericQuadTree
{
    public class TreeObject
    {
        public Point Location { get; private set; }

        private object _parentTree;
        private object _parentNode;

        public TreeObject(Point location)
        {
            Location = location;
        }

        internal void UpdateTreeReference<T>(QuadTree<T> parentTree) where T : TreeObject
        {
            _parentTree = parentTree;
            _parentNode = parentTree.GetNodeAtLocation(Location);
            UpdatePosition<T>(Location);
        }

        public void UpdatePosition<T>(Point newPosition) where T : TreeObject
        {
            Location = newPosition;

            if (_parentTree == null)
                return;

            var parentTree = (QuadTree<T>) _parentTree;
            var parentNode = (QuadNode<T>) _parentNode;

            var maxX = parentTree.Location.X + parentTree.TreeWidth;
            var maxY = parentTree.Location.Y + parentTree.TreeHeight;

            if ((newPosition.X >= parentTree.Location.X && newPosition.X <= maxX) &&
                (newPosition.Y >= parentTree.Location.Y && newPosition.Y <= maxY))
            {
                var newParent = parentTree.GetNodeAtLocation(newPosition);


                if (_parentNode != null)
                    parentNode.RemoveObject((T) this);

                _parentNode = newParent;

                if (_parentNode != null)
                    parentNode.AddObject((T) this);
            }
            else
            {
                //Object has moved out of the boundaries of the tree
                if (_parentNode != null)
                    parentNode.RemoveObject((T) this);

                _parentNode = null;
            }
        }
    }
}